import { AppDataSource } from "@/config/database";
import { Services } from "@/entities/basis/services.entity";
import { ErrorHandler } from "@/middlewares/error.middleware";
import { TokenPayload } from "@/utils/token.util";
import { Context } from "koa";

export interface IBody extends Partial<Services> {
    id: string;
}

/** 更新服务 */
export async function updateService(ctx: Context) {
    const body = ctx.request.body as IBody;
    const user: TokenPayload = ctx.state.user;

    // 验证参数
    validateParams(body.id, body.code, body.name);

    // 检查服务是否存在
    const existingService = await checkServiceExists(body.id);

    // 检查服务编号是否重复（如果修改了编号）
    if (body.code && body.code !== existingService.code) {
        await checkServiceCodeExists(body.code);
    }

    // 更新服务
    const updatedService = await updateServiceData(existingService, body, user);

    ctx.status = 200;
    ctx.body = updatedService;
}

/** 验证参数 */
const validateParams = (id: string, code?: string, name?: string) => {
    if (!id) {
        throw new ErrorHandler('服务ID不能为空', 400);
    }
    
    if (code && !code.trim()) {
        throw new ErrorHandler('服务编号不能为空', 400);
    }
    
    if (name && !name.trim()) {
        throw new ErrorHandler('服务名称不能为空', 400);
    }
}

/** 检查服务是否存在 */
const checkServiceExists = async (id: string) => {
    const serviceRepository = AppDataSource.getRepository(Services);
    
    const service = await serviceRepository.findOne({
        where: { id }
    });
    
    if (!service) {
        throw new ErrorHandler('服务不存在', 404);
    }
    
    return service;
}

/** 检查服务编号是否已存在 */
const checkServiceCodeExists = async (code: string) => {
    const serviceRepository = AppDataSource.getRepository(Services);
    
    const existingService = await serviceRepository.findOne({
        where: { code }
    });
    
    if (existingService) {
        throw new ErrorHandler('服务编号已存在', 409);
    }
}

/** 更新服务数据 */
const updateServiceData = async (service: Services, body: IBody, user: TokenPayload) => {
    const serviceRepository = AppDataSource.getRepository(Services);
    
    // 更新必填字段
    if (body.code) {
        service.code = body.code.trim();
    }
    
    if (body.name) {
        service.name = body.name.trim();
    }
    
    if (body.status) {
        service.status = body.status;
    }
    
    // 更新可选字段
    if (body.description !== undefined) {
        service.description = body.description ? body.description.trim() : undefined;
    }
    
    if (body.category !== undefined) {
        service.category = body.category ? body.category.trim() : undefined;
    }
    
    if (body.duration !== undefined) {
        service.duration = body.duration;
    }
    
    if (body.technicianLevel !== undefined) {
        service.technicianLevel = body.technicianLevel ? body.technicianLevel: undefined;
    }
    
    if (body.cashPrice !== undefined) {
        service.cashPrice = body.cashPrice;
    }

    if (body.integral !== undefined) {
        service.integral = body.integral;
    }
    
    if (body.cardPrice !== undefined) {
        service.cardPrice = body.cardPrice;
    }
    
    // 更新修改信息
    service.updatedBy = user.id;
    service.updatedAt = new Date();
    
    try {
        return await serviceRepository.save(service);
    } catch (error) {
        // 处理数据库保存错误
        if (error.code === 'ER_DUP_ENTRY') {
            throw new ErrorHandler('服务编号已存在', 409);
        }
        throw new ErrorHandler('更新服务信息失败', 500);
    }
} 